package com.ch999.detect.View.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.ViewSwitcher;

import com.bumptech.glide.Glide;
import com.ch999.detect.AppBaseActivity;
import com.ch999.detect.R;
import com.ch999.detect.View.adapter.CheckFactionAdatper;
import com.ch999.detect.View.adapter.FacationAdatper;
import com.ch999.detect.View.dialog.DetectConnDialog;
import com.ch999.detect.View.dialog.NetTitleDialog;
import com.ch999.detect.View.dialog.NotCreat2CordDialog;
import com.ch999.detect.View.dialog.RestDetectDialog;
import com.ch999.detect.View.dialog.Show2CodeDialog;
import com.ch999.detect.View.dialog.WifiUnOpenDialog;
import com.ch999.detect.constant.EventType;
import com.ch999.detect.constant.SpType;
import com.ch999.detect.mode.DetctControl;
import com.ch999.detect.mode.bean.GoodsBjgz;
import com.ch999.detect.mode.bean.RecoverBasketEntity;
import com.ch999.detect.utils.CommUtils;
import com.ch999.detect.utils.DeviceUtils;
import com.ch999.detect.utils.SharePrefUtil;
import com.ch999.detect.utils.TwoCadeUtils;
import com.github.mzule.activityrouter.annotation.Module;
import com.github.mzule.activityrouter.annotation.Router;
import com.google.gson.Gson;
import com.scorpio.mylib.Routers.MDRouters;
import com.scorpio.mylib.Tools.Tools;
import com.scorpio.mylib.http.iface.DataResponse;
import com.scorpio.mylib.ottoBusProvider.BusEvent;
import com.scorpio.mylib.ottoBusProvider.MyBusProvide;
import com.squareup.otto.Subscribe;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import rx.functions.Action1;

import static com.ch999.detect.R.id.btn_once_check;
import static com.ch999.detect.constant.SpType.KEY_BAND_ID;
import static com.ch999.detect.constant.SpType.KEY_DATE;
import static com.ch999.detect.constant.SpType.KEY_PHONE_DATA;
import static com.ch999.detect.constant.SpType.KEY_PHONE_PID;
import static com.ch999.detect.constant.SpType.KEY_POSATION;
import static com.ch999.detect.utils.DeviceUtils.getTotalInternalMemorySize;


@Module("detect")
@Router({"revaluation"})
public class MainActivityApp extends AppBaseActivity implements View.OnClickListener {


    final public static String EXTRA_ACTION = "action";
    final public static String EXTRA_POSATION = "posation";
    final public static String EXTRA_DATA = "attr_data";

    TextView tvMian;

    TextView tvPhone;
    TextView tvPhone2;

    TextView tvNeicun;
    TextView tvNeicun2;
    TextView tvRongliang;
    TextView tvRongliang2;

    TextView tvResetCheck;
    ListView rvFucationList;
    LinearLayout activityMain;

    Button mBtnOnceCheck;
    ViewSwitcher viewSwitcher;

    ImageView imgPup;
    ImageView img_close;


    String[] mFacation = new String[]{"无线功能", "通话功能", "触摸功能", "屏幕显示", "充电功能", "摄像功能", "指南针功能"};
    String[] mCheckString = new String[]{"是否进水", "指纹功能", "定位功能", "按键功能"};
    String[] mDefNotDisString = new String[]{"开机情况"};

    ImageView imgMenu;
    RelativeLayout llRootTitle;
    TextView tvBottomAgain;
    TextView tv_main;
    TextView tvImei;


    private FacationAdatper mFacationAdatper;

    /**
     * 是否检测到最后位置
     */
    private boolean isFootPosation;
    private Map<String, Class> mActivityList;
    private Map<String, Integer> mFacationImageList;
    private Map<String, Integer> mNoFacationImageList;

    private DetectConnDialog mDetectConnDialog;
    /**
     * 检测到的位置
     */
    private int mPosation = -1;
    private String model;

    /**
     * 所有机型属性
     */
    List<GoodsBjgz.AttrBean> mPhoneAttr = new ArrayList<>();

    /**
     * 多选的机型属性
     */
    List<GoodsBjgz.AttrBean> mCheckBoxAttr = new ArrayList<>();

    /**
     * 默认不显示
     */
    List<GoodsBjgz.AttrBean> mDefDisArrt = new ArrayList<>();


    private Show2CodeDialog mShow2CodeDialog;
    private RestDetectDialog mRestDetectDialog;
    private CheckFactionAdatper mCheckFactionAdatper;
    private View mFootView;
    private String mManufacturer;
    private NetTitleDialog mNetTitleDialog;
    private LinearLayout mView;
    private LinearLayout mRootView;
    private NotCreat2CordDialog mNotCreat2CordDialog;
    private WifiUnOpenDialog mWifiUnOpenDialog;


    private boolean isApp;
    private ViewFlipper mViewFlipper;
    private String mApikey;

    @Override
    public int getLayoutId() {
        return R.layout.activity_detectmain;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isApp = Boolean.parseBoolean(getIntent().getExtras().getString("isApp"));

        if (isApp) {
            img_close.setVisibility(View.VISIBLE);
            tv_main.setText("本机估价");
        }

        String appname = getIntent().getExtras().getString("appname");
        if (!TextUtils.isEmpty(appname)) {
            tv_main.setText(appname);
        }

        if (getIntent().getExtras().containsKey("apikey")) {
            mApikey = getIntent().getExtras().getString("apikey");
        } else {
            //默认都是0 。兼容主战
            mApikey = "0";
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyBusProvide.getInstance().unregister(this);

    }

    @Override
    public void initView(Bundle savedInstanceState) {

        MyBusProvide.getInstance().register(this);
        SharePrefUtil.getInstance(mContext).putInt(KEY_POSATION, -1);

        initBaseActivityList();

        initdata();

        initInfo();

        initlistener();

        getPhoneAttr();

        //checkWifi();

    }

    @Override
    public void findView() {
        tvMian = (TextView) findViewById(R.id.tv_main);

        tvPhone = (TextView) findViewById(R.id.tv_phone);
        tvPhone2 = (TextView) findViewById(R.id.tv_phone2);

        tvNeicun = (TextView) findViewById(R.id.tv_neicun);

        tvNeicun2 = (TextView) findViewById(R.id.tv_neicun2);
        tvRongliang = (TextView) findViewById(R.id.tv_rongliang);
        tvRongliang2 = (TextView) findViewById(R.id.tv_rongliang2);

        tvResetCheck = (TextView) findViewById(R.id.tv_reset_check);

        rvFucationList = (ListView) findViewById(R.id.rv_fucation_list);
        activityMain = (LinearLayout) findViewById(R.id.activity_main);

        mBtnOnceCheck = (Button) findViewById(btn_once_check);

        viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitch);

        imgMenu = (ImageView) findViewById(R.id.img_menu);
        llRootTitle = (RelativeLayout) findViewById(R.id.ll_root_title);
        tvBottomAgain = (TextView) findViewById(R.id.tv_bottom_again);
        img_close = (ImageView) findViewById(R.id.img_close);
        tv_main = (TextView) findViewById(R.id.tv_main);
        tvImei = (TextView) findViewById(R.id.tv_iemi);

        mViewFlipper = (ViewFlipper) findViewById(R.id.viewflipper_news);

    }

    private void createWifiDialog() {


        if (mWifiUnOpenDialog == null) {
            mWifiUnOpenDialog = new WifiUnOpenDialog(mContext, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getAppDetailSettingIntent();
                }
            });
        }

        mWifiUnOpenDialog.show();
    }


    /**
     * 获取应用详情页面intent
     *
     * @return
     */
    private void getAppDetailSettingIntent() {
        if (android.os.Build.VERSION.SDK_INT > 10) {
            // 3.0以上打开设置界面，也可以直接用ACTION_WIRELESS_SETTINGS打开到wifi界面
            startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
        } else {
            startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
        }
    }


    private void initNetData() {

        showLodingDialog();
        getPhoneData();

    }


    /**
     * 获取手机属性
     */
    public void getPhoneAttr() {

        String data = SharePrefUtil.getInstance(mContext).getString(KEY_PHONE_DATA);//保存手机数据

        if (data != null) {
            Gson gson = new Gson();
            GoodsBjgz goodsBjgz = gson.fromJson(data, GoodsBjgz.class);

            sortPhoneData(goodsBjgz);

            //startAutoDetectActivity(0);

        } else {

            initdata();
        }

    }

    /**
     * 获取机型数据
     */
    private void getPhoneData() {

        showLodingDialog();
        DetctControl.getPhoneData(mContext, model, new DetctControl.JiXinDataResponse() {
            @Override
            public void onEmpty() {

                //Toast.makeText(mContext, "选择机型", Toast.LENGTH_LONG).show();
                //选择参数类型
                getTallData();

            }

            @Override
            public void onSucc(Object response) {

                hideLodingDialog();

                GoodsBjgz goodsBjgz = (GoodsBjgz) response;
                startAutoDetectActivity(0, true, goodsBjgz);

                sortPhoneData(goodsBjgz);
//
                setBtnCheckText(-1); //重新检测

                //跳转检测界面

                //getTallData();

            }

            @Override
            public void onFail(String error) {
                hideLodingDialog();
                // Toast.makeText(mContext, "网络异常", Toast.LENGTH_SHORT).show();

                showNetConnetDialog();
            }
        });
    }

    private void showNetConnetDialog() {
        if (mNetTitleDialog == null) {

            mNetTitleDialog = new NetTitleDialog(mContext, new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }
        mNetTitleDialog.show();

    }

    private void getTallData() {
        DetctControl.geTallGoods(mContext, new DataResponse() {
            @Override
            public void onSucc(Object response) {

                hideLodingDialog();
                startAnimActivity(JiXingSelectActivity.class);

            }

            @Override
            public void onFail(String error) {
                hideLodingDialog();
                Toast.makeText(mContext, "网络异常", Toast.LENGTH_SHORT).show();
            }
        });
    }


    //排序设置属性
    public void sortPhoneData(GoodsBjgz goodsBjgz) {

        initBaseActivityList();

        if (goodsBjgz != null && goodsBjgz.getAttr().size() == 0) {

            return;
        }

        mPhoneAttr.clear();
        mCheckBoxAttr.clear();
        mDefDisArrt.clear();

        List<GoodsBjgz.AttrBean> attrs = goodsBjgz.getAttr();
        for (GoodsBjgz.AttrBean attr : attrs) {

            String tpname = attr.getTpname();

            for (String fac : mFacation) {

                if (fac.equals(tpname)) {
                    mPhoneAttr.add(attr);
                    mNoFacationImageList.put(fac, mFacationImageList.get(fac));
                }
            }


            if (attr.getIsmul().equals("1")) {

                attr.setCheckBox(true);  //其他默认为false;
                mCheckBoxAttr.add(attr);
            }

            //寻找开机项
            for (String notDis : mDefNotDisString) {
                if (notDis.equals(tpname)) {
                    attr.setItemPosation(0);
                    mDefDisArrt.add(attr);
                }
            }
        }

        mFacationImageList.clear();

        mFacationImageList = mNoFacationImageList;
        attrs.removeAll(mPhoneAttr);
        attrs.removeAll(mCheckBoxAttr);
        attrs.removeAll(mDefDisArrt);
        mCheckBoxAttr.removeAll(mPhoneAttr);
        mCheckBoxAttr.removeAll(mDefDisArrt);

        mPhoneAttr.addAll(attrs);

        //mPhoneAttr.addAll(mCheckBoxAttr); //取消多选的加入

        mFacationAdatper.setData(mPhoneAttr, mFacationImageList);

        //设置全局变量
        CommUtils.mPhoneAttr = mPhoneAttr;
        //设置多选
        CommUtils.mCheckBoxAttr = mCheckBoxAttr;

        if (mPhoneAttr != null) {
            int arrtSize = mPhoneAttr.size();

            if (mCheckBoxAttr != null && mCheckBoxAttr.size() > 0) {
                CommUtils.mAttrSize = arrtSize + 1;
            }
        }
    }


    private void initlistener() {


        tvResetCheck.setOnClickListener(this);
        imgMenu.setOnClickListener(this);
        tvBottomAgain.setOnClickListener(this);
        mBtnOnceCheck.setOnClickListener(this);
        img_close.setOnClickListener(this);
    }


    private void initdata() {

        mFacationAdatper = new FacationAdatper(mContext, mPhoneAttr, mFacation.length, mFacationImageList);


        LayoutInflater inflate = LayoutInflater.from(mContext);

        mView = (LinearLayout) inflate.inflate(R.layout.item_foot_layout, null);

        mRootView = (LinearLayout) mView.findViewById(R.id.ll_chick_fild);
        mView.setVisibility(View.GONE);
        rvFucationList.addFooterView(mView);


        rvFucationList.setAdapter(mFacationAdatper);

        mFacationAdatper.setOnClickItemListener(onClickItemListener);


        setBtnCheckText(SharePrefUtil.getInstance(mContext).getInt(KEY_POSATION));


    }

    private void setBtnCheckText(int posation) {


        if (posation < mPhoneAttr.size() - 1 && posation >= 0) {

            tvBottomAgain.setText("继续检查");
            tvResetCheck.setVisibility(View.VISIBLE);
        } else if (posation == -1) {
            tvBottomAgain.setText("一键检查");
            tvResetCheck.setVisibility(View.GONE);
        } else {

            tvResetCheck.setVisibility(View.VISIBLE);
            if (mPhoneAttr != null && mPhoneAttr.size() - 1 == posation) {

                if (isApp) {
                    tvBottomAgain.setText("检测完成，查看估价");

                } else {
                    tvBottomAgain.setText(R.string.str_look_check_book);

                }
                isFootPosation = true;


            }

        }
    }

    private void initBaseActivityList() {
        mActivityList = new HashMap<>();
        mFacationImageList = new HashMap<>();
        mNoFacationImageList = new HashMap<>();


        CommUtils.mActivityList = mActivityList;

        mFacationImageList.put(mFacation[0], R.drawable.wifi);
        mFacationImageList.put(mFacation[1], R.drawable.call);
        mFacationImageList.put(mFacation[2], R.drawable.ontouch);
        mFacationImageList.put(mFacation[3], R.drawable.screen);
        mFacationImageList.put(mFacation[4], R.drawable.charging);
        mFacationImageList.put(mFacation[5], R.drawable.comear);
        mFacationImageList.put(mFacation[6], R.drawable.znz);

    }

    private void initInfo() {

        mManufacturer = DeviceUtils.getManufacturer();

        model = DeviceUtils.getModel();

        long totalMemorySize = DeviceUtils.getTotalMemorySize(mContext);
        //long availableExternalMemorySize = DeviceUtils.getAvailableExternalMemorySize();
        long availableInternalMemorySize = getTotalInternalMemorySize();

        String phoneStr = mManufacturer + " - " + model;
        tvPhone.setText(phoneStr);
        tvPhone2.setText(phoneStr);
        String text = DeviceUtils.formatMemoryFileSize(totalMemorySize, true);
        tvNeicun.setText(text);
        tvNeicun2.setText(text);

        String text1 = DeviceUtils.formatPhoneCardFileSize(availableInternalMemorySize, true);
        tvRongliang.setText(text1);
        tvRongliang2.setText(text1);


        if (!Tools.checkoutPermissions(mContext, new String[]{
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA
        })) {
            new RxPermissions(this).request(Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA)
                    .subscribe(new Action1<Boolean>() {
                        @Override
                        public void call(Boolean aBoolean) {
                            if (aBoolean) {
                                tvImei.setText("IMEI: " + DeviceUtils.getIMEI(mContext));
                            }
                        }
                    });
        } else {
            tvImei.setText("IMEI: " + DeviceUtils.getIMEI(mContext));
        }

        DetctControl.GetNewRecoverBasket(mContext, model, new DataResponse() {
            @Override
            public void onSucc(Object o) {
                ArrayList<RecoverBasketEntity> recoverBasketEntities = (ArrayList<RecoverBasketEntity>) o;

                mViewFlipper.setVisibility(View.VISIBLE);
                for (RecoverBasketEntity recoverBasketEntity : recoverBasketEntities) {
                    mViewFlipper.addView(createBasket(recoverBasketEntity));
                }
            }

            @Override
            public void onFail(String s) {

            }
        });


    }


    /**
     * 功能列表监听
     */
    FacationAdatper.OnClickItemListener onClickItemListener = new FacationAdatper.OnClickItemListener() {
        @Override
        public void onClickItemListener(int posation, GoodsBjgz.AttrBean attrBean) {

            if (mActivityList.containsKey(attrBean.getTpname())) {

                Class aClass = mActivityList.get(attrBean.getTpname());

                if (aClass != null) {

                    Intent intent = new Intent(mContext, aClass);
                    intent.putExtra(EXTRA_POSATION, posation);
                    intent.putExtra(EXTRA_DATA, attrBean);

                    startActivity(intent);
                } else {
                    Log.e(TAG, "onClickItemListener: ============Activiy为空");
                }


            } else {

            }

        }
    };


    /**
     * 单机事件处理
     *
     * @param view
     */
    public void onClick(View view) {
        int i = view.getId();
        if (i == btn_once_check || i == R.id.tv_bottom_again) {//从头开始

            btnOnceCheck();
            //   viewSwitcher.setDisplayedChild(1);


        } else if (i == R.id.tv_reset_check) {/**
         * 0.弹出对话框
         * 1.清除数据
         * 2.位置归0
         * 3.重新获取网络数据
         */

            createRestDetectDialog();
            if (mView != null) {
                mView.setVisibility(View.GONE);
            }
            String string = SharePrefUtil.getInstance(mContext).getString(KEY_DATE);

            if (TextUtils.isEmpty(string)) {
                ResetCheck();

            } else {
                mRestDetectDialog.showDialog(string);
            }


        } else if (i == R.id.img_menu) {
            startAnimActivity(DeviceInfoActivity.class);

        } else if (i == R.id.img_close) {
            finish();
        }
    }

    /**
     * 创建重新检测的dialog
     */
    private void createRestDetectDialog() {
        if (mRestDetectDialog == null) {

            mRestDetectDialog = new RestDetectDialog(mContext, new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (view.getId() == R.id.btn_reset) {
                        ResetCheck();
                    }

                }
            });
        }
    }

    /**
     * 从头开始，一键清空
     */
    private void ResetCheck() {
        mPosation = -1;

        isFootPosation = false;

        mFacationAdatper.showItemNumb = 0; //重置适配器

        mRootView.removeAllViews();

        SharePrefUtil.getInstance(mContext).putInt(KEY_POSATION, -1); //从头开始
        SharePrefUtil.getInstance(mContext).putString(KEY_PHONE_PID, null); //清除手机手机数据
        SharePrefUtil.getInstance(mContext).putString(KEY_BAND_ID, null); //清除手机手机数据
        setBtnCheckText(-1);

        getPhoneData();

    }


    /**
     * 从头开始，一键清空
     */
    private void ResetTallData() {
        mPosation = -1;

        isFootPosation = false;

        mFacationAdatper.showItemNumb = 0; //重置适配器

        mRootView.removeAllViews();

        SharePrefUtil.getInstance(mContext).putInt(KEY_POSATION, -1); //从头开始
        SharePrefUtil.getInstance(mContext).putString(KEY_PHONE_PID, null); //清除手机手机数据
        SharePrefUtil.getInstance(mContext).putString(KEY_BAND_ID, null); //清除手机手机数据
        setBtnCheckText(-1);

        //Toast.makeText(mContext, "选择机型", Toast.LENGTH_LONG).show();
        //选择参数类型
        getTallData();

    }

    /**
     * 一键检测
     */

    private void btnOnceCheck() {

        if (mPosation == -1) {
            initNetData();
        } else if (isFootPosation) {
            //提交检测

            saveAttr();

        } else {

            if (mDetectConnDialog == null) {

                createDialog();
            }

            mDetectConnDialog.show(mPosation + 1);
        }


    }


    private View createBasket(RecoverBasketEntity recoverBasketEntity) {

        View inflate = View.inflate(mContext, R.layout.message_huishou, null);

        CircleImageView imgIcon = (CircleImageView) inflate.findViewById(R.id.img_icon);
        Glide.with(mContext).load(recoverBasketEntity.getUserface()).crossFade().into(imgIcon);
        TextView tvUserName = (TextView) inflate.findViewById(R.id.tv_user_name);
        tvUserName.setText(recoverBasketEntity.getUsername() + "：");

        TextView tvUserScren = (TextView) inflate.findViewById(R.id.tv_user_scren);
        tvUserScren.setText(recoverBasketEntity.getTimeinfo());
        String text = " <font color='#FF0000'> ¥" + recoverBasketEntity.getPrice() + " </>" + "回收了" + recoverBasketEntity.getProductName() + " " + recoverBasketEntity.getProductColor();
        Spanned spanned = Html.fromHtml(text);

        tvUserScren.setText(spanned);
        return inflate;

    }

    /**
     * 提交检测
     */
    private void saveAttr() {


        if (mPhoneAttr == null && mDefDisArrt == null) {
            return;
        }


        boolean aBoolean = SharePrefUtil.getInstance(mContext).getBoolean(SpType.KEY_COUNT);

        if (!aBoolean) {

            if (mNotCreat2CordDialog == null) {
                mNotCreat2CordDialog = new NotCreat2CordDialog(mContext, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });

            }
            mNotCreat2CordDialog.show();

        } else {
            String mImei;
            if (!Tools.checkoutPermissions(mContext, new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_PHONE_STATE})) {
                new RxPermissions(this).request(Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_PHONE_STATE)
                        .subscribe(new Action1<Boolean>() {
                            @Override
                            public void call(Boolean aBoolean) {
                                if (aBoolean) {
                                    saveAttr(DeviceUtils.getIMEI(mContext), isApp);
                                }
                            }
                        });
            } else {
                saveAttr(DeviceUtils.getIMEI(mContext), isApp);

            }
        }
    }

    private void saveAttr(String mImei, final boolean isAPP) {
        List<GoodsBjgz.AttrBean> arrtList = new ArrayList<>();
        arrtList.addAll(mPhoneAttr);
        arrtList.addAll(mDefDisArrt);
        arrtList.addAll(mCheckBoxAttr);

        String paramsString = getParamsString(arrtList);

        if (paramsString != null) {
            showLodingDialog();
            DetctControl.saveAttr(mContext, paramsString, mImei, isAPP,mApikey, new DataResponse() {
                @Override
                public void onSucc(final Object response) {

                    if (isAPP) {
                        new MDRouters.Builder().build((String) response).create(mContext).go();
                        finish();
                    } else {
                        show2Card(response);
                    }
                }

                @Override
                public void onFail(String error) {
                    hideLodingDialog();

                    showNetConnetDialog();
                }
            });
        }
    }

    private void show2Card(final Object response) {
        final String filePath = TwoCadeUtils.getFileRoot(MainActivityApp.this) + File.separator + "qr_" + System.currentTimeMillis() + ".jpg";

        new Thread(new Runnable() {
            @Override
            public void run() {

                boolean success = TwoCadeUtils.createQRImage(response.toString() + "&DeviceId=1", 800, 800, null, filePath);
                if (success) {

                    hideLodingDialog();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            if (mShow2CodeDialog == null) {
                                mShow2CodeDialog = new Show2CodeDialog(mContext);
                            }

                            mShow2CodeDialog.showDialog(filePath);

                        }
                    });

                } else {
                    Toast.makeText(mContext, "生成失败", Toast.LENGTH_SHORT).toString();
                }
            }

        }).start();
    }


    public String getParamsString(List<GoodsBjgz.AttrBean> phoneAttr) {

        if (phoneAttr == null) {
            throw new RuntimeException("phone数据为空");
        }

        StringBuffer sBuffer = new StringBuffer();

        int size = phoneAttr.size();
        for (int i = 0; i < size; i++) {

            if (i != size - 1) {
                sBuffer.append(phoneAttr.get(i).getParams() + ",");
            } else {
                sBuffer.append(phoneAttr.get(i).getParams());
            }
        }


        System.out.println(sBuffer);
        return sBuffer.toString();
    }


    /**
     * 启动指定启动Activity
     *
     * @param posation
     * @param isAuto   是否自动检测 非常规项
     */
    private void startAutoDetectActivity(int posation, boolean isAuto, GoodsBjgz bjgz) {

        Intent intent = new Intent(mContext, NewDetectActivity.class);
        intent.putExtra("bjgz", bjgz);
        intent.putExtra("isAPP", isApp);
        intent.putExtra("apikey", mApikey);
        startActivity(intent);


//        if (isAuto) {
//
//            SharePrefUtil.getInstance(mContext).putBoolean(SpType.KEY_IS_POSATION_ZEROR, true);
//
//        } else {
//
//            SharePrefUtil.getInstance(mContext).putBoolean(SpType.KEY_IS_POSATION_ZEROR, false);
//
//        }
//
//        Intent intent = CommUtils.getInstance().getAutoDetectActivityIntent(mContext, posation);
//        if (intent == null) {
//            return;
//        }
//
//        startActivity(intent);

    }


    /**
     * 创建根部布局
     *
     * @param checkBoxAttr
     * @return
     */
    public View createFootView(List<GoodsBjgz.AttrBean> checkBoxAttr) {


        LayoutInflater inflate = LayoutInflater.from(mContext);

        int size = checkBoxAttr.size();
        int line = size / 2;

        int num = 0;

        for (int i = 0; i < line; i++) {


            View chekView = inflate.inflate(R.layout.item_foot_check, null);

            CheckBox checkBoxLeft = (CheckBox) chekView.findViewById(R.id.checkBox_left);


            GoodsBjgz.AttrBean attrBean1 = checkBoxAttr.get(num);
            int itemPosation = attrBean1.getItemPosation();
            String name = attrBean1.getValues().get(1).getName();


            checkBoxLeft.setText(name);
            checkBoxLeft.setOnCheckedChangeListener(mCheckedChangeListener);
            checkBoxLeft.setTag(num);

            checkBoxLeft.setChecked(itemPosation == 1 ? true : false);

            CheckBox checkBoxRight = (CheckBox) chekView.findViewById(R.id.checkBox_right);

            GoodsBjgz.AttrBean attrBean = checkBoxAttr.get(num + 1);
            itemPosation = attrBean.getItemPosation();
            name = attrBean.getValues().get(1).getName();

            checkBoxRight.setText(name);
            checkBoxRight.setOnCheckedChangeListener(mCheckedChangeListener);
            checkBoxRight.setTag(num + 1);
            checkBoxRight.setChecked(itemPosation == 1 ? true : false);

            num += 2;

            mRootView.addView(chekView);
        }

        int yu = size % 2;

        if (yu > 0) {

            View chekView = inflate.inflate(R.layout.item_foot_check, null);

            CheckBox checkBoxLeft = (CheckBox) chekView.findViewById(R.id.checkBox_left);
            GoodsBjgz.AttrBean attrBean = checkBoxAttr.get(size - 1);
            int itemPosation = attrBean.getItemPosation();
            String name = attrBean.getValues().get(1).getName();
            checkBoxLeft.setText(name);
            checkBoxLeft.setOnCheckedChangeListener(mCheckedChangeListener);
            checkBoxLeft.setChecked(itemPosation == 1 ? true : false);

            CheckBox checkBoxRight = (CheckBox) chekView.findViewById(R.id.checkBox_right);
            checkBoxRight.setVisibility(View.INVISIBLE);

            mRootView.addView(chekView);
        }

        return mView;

    }

    CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            if (mCheckBoxAttr == null) {

                return;
            }

            Object tag = compoundButton.getTag();
            if (tag instanceof Integer) {
                int posation = (int) tag;

                if (posation < mCheckBoxAttr.size()) {

                    GoodsBjgz.AttrBean attrBean = mCheckBoxAttr.get(posation);
                    attrBean.setItemPosation(b ? 1 : 0);

                }

            }


        }
    };

    @Subscribe
    public void onPostEvent(BusEvent postEvent) {
        int action = postEvent.getAction();
        if (action == EventType.MSG_ONCLICK_RESET.ordinal()) {
            ResetTallData();
            return;
        } else if (action == EventType.MSG_SELECT_JIXIN_SUCCESS.ordinal()) {
            initNetData();
        }
    }


    public void createDialog() {
        mDetectConnDialog = new DetectConnDialog(mContext, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int i = view.getId();
                if (i == R.id.btn_0) {
                    startAutoDetectActivity(mPosation + 1, true, null);


                } else if (i == R.id.btn_1) {//从头开始
                    ResetCheck();


                }
            }
        });
    }


}
